/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.SABM;

import session.TX.StakeholderAccountSBRemote;
import managedBean.TX.CustomerIOTRPortal.FakeMainPortalMB;
import entity.Stakeholder;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import Web_Helper.*;
import java.io.IOException;
import javax.mail.PasswordAuthentication;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import session.CM.PortalManagementSB;
import session.TX.ULPSBRemote;

/**
 *
 * @author Randall Chia
 */
@ManagedBean(name = "StakeholderPointsMB")
@SessionScoped
public class StakeholderPointsMB {
    
    private List<pointPurchaseItem> purchaseList;    
    private pointPurchaseItem selectedPurchaseItem;
    private double purchasePrice;
    private Date transactionTimestamp;
    private String customerEmail;
    private Integer points;
    private String statusMessage;
    
    private String purchaseStatusMSG;

    @EJB
    private StakeholderAccountSBRemote stakeholderManager;
    @EJB
    private ULPSBRemote ulpRemote;
    @EJB
    private PortalManagementSB portalManagementSB;

    /** Creates a new instance of StakeholderPointsMB */
    public StakeholderPointsMB() {
        purchaseList = new ArrayList<pointPurchaseItem>();
        purchaseList.add(new pointPurchaseItem(1000, 20.0));
        purchaseList.add(new pointPurchaseItem(5000, 90.0));
        purchaseList.add(new pointPurchaseItem(10000, 170.0));
    }
    
    public Integer retrieveStakeholderLoyaltyPoints() {
        String stakeholderName = (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderName").toString());
        List<Stakeholder> stkList = stakeholderManager.getSpecificStakeholders(stakeholderName);
        if (!stkList.isEmpty()) {
            return stkList.get(0).getLoyaltyPoints();
        }
        return 0;
    }

    //Perform validation of a payment for buying loyalty points from TCube
    public void validatePayment() {
        
        boolean validationResult = false;
        try {
            validationResult = Helper_PaymentValidator.validatePayment();
        } catch (IOException e) {
        }
        
        if (validationResult == true) {
            System.out.println("Payment Validation: SUCCESS");
            
            transactionTimestamp = new Date();
            
            String stakeholderName = (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderName").toString());            
            
            stakeholderManager.givePointsToStakeholder(stakeholderName, selectedPurchaseItem.getQuantity());
            System.out.println("Gave " + selectedPurchaseItem.getQuantity() + " points to " + stakeholderName);

            //create purchase log entry
            ulpRemote.createPointPurchaseEntry_Stakeholder(transactionTimestamp, stakeholderName, selectedPurchaseItem.getPrice());
            
            
            purchaseStatusMSG = "<h4>LOYALTY POINTS PURCHASED</h4>"
                    + "<h4>Timestamp: </h4>" + transactionTimestamp + "<br/>"
                    + "<h4>Buyer: </h4>" + stakeholderName + "<br/>"
                    + "<h4>Points Purchased: </h4>" + selectedPurchaseItem.getQuantity()
                    ;
            
            
            selectedPurchaseItem = null;
        }//end THEN block
        else {
            System.out.println("Payment Validation: FAIL");
        }
        
    }
    
    public void stakeholderAwardPoints(ActionEvent event) {
        boolean status = ulpRemote.stalkerholderAwardPoints(FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("stakeholderName").toString()
                , points, customerEmail);
        System.out.println("Status:"+ status);
        if(status==true)
        {
            //MAIL START
                   
            String emailMessage = "Congratulations ! You have being awarded" + points + " points by " + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderName").toString();


            String senderEmail = portalManagementSB.getEmailFrom();
            String senderPassword = portalManagementSB.getEmailPassword();
            EmailSender emailsender = new EmailSender(senderEmail, senderPassword);
            String[] recepients = {customerEmail};

            try{
                emailsender.postMail(recepients, "FoodSage Loyalty Points Received", emailMessage, senderEmail);
            }catch(javax.mail.MessagingException e){
            }
                 
            //MAIL END
            setStatusMessage("Points awarded successfully");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Result: " + getStatusMessage(), ""));
        }
        else{
             setStatusMessage("Points not awarded");
              FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Result: " + getStatusMessage(), ""));
    }
        
    }
    
    public void updatePurchasePrice() {
        purchasePrice = selectedPurchaseItem.getPrice();
    }

    /**
     * @return the purchaseList
     */
    public List<pointPurchaseItem> getPurchaseList() {
        return purchaseList;
    }

    /**
     * @param purchaseList the purchaseList to set
     */
    public void setPurchaseList(List<pointPurchaseItem> purchaseList) {
        this.purchaseList = purchaseList;
    }

    /**
     * @return the selectedPurchaseItem
     */
    public pointPurchaseItem getSelectedPurchaseItem() {
        return selectedPurchaseItem;
    }

    /**
     * @param selectedPurchaseItem the selectedPurchaseItem to set
     */
    public void setSelectedPurchaseItem(pointPurchaseItem selectedPurchaseItem) {
        this.selectedPurchaseItem = selectedPurchaseItem;
    }

    /**
     * @return the purchasePrice
     */
    public double getPurchasePrice() {
        return purchasePrice;
    }

    /**
     * @param purchasePrice the purchasePrice to set
     */
    public void setPurchasePrice(double purchasePrice) {
        this.purchasePrice = purchasePrice;
    }

    /**
     * @return the transactionTimestamp
     */
    public Date getTransactionTimestamp() {
        return transactionTimestamp;
    }

    /**
     * @param transactionTimestamp the transactionTimestamp to set
     */
    public void setTransactionTimestamp(Date transactionTimestamp) {
        this.transactionTimestamp = transactionTimestamp;
    }

    /**
     * @return the customerEmail
     */
    public String getCustomerEmail() {
        return customerEmail;
    }

    /**
     * @param customerEmail the customerEmail to set
     */
    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    /**
     * @return the points
     */
    public Integer getPoints() {
        return points;
    }

    /**
     * @param points the points to set
     */
    public void setPoints(Integer points) {
        this.points = points;
    }

    /**
     * @return the statusMessage
     */
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * @param statusMessage the statusMessage to set
     */
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }
    
   

    /**
     * @return the PurchaseStatusMSG
     */
    public String getPurchaseStatusMSG() {
        return purchaseStatusMSG;
    }

    /**
     * @param PurchaseStatusMSG the PurchaseStatusMSG to set
     */
    public void setPurchaseStatusMSG(String purchaseStatusMSG) {
        this.purchaseStatusMSG = purchaseStatusMSG;
    }

}
